package com.solution.webutil;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.rmi.RemoteException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.solution.delegate.ImageTypeServiceDelegate;
import com.solution.exception.DelegateException;
import com.solution.exception.ServiceBeanException;
import com.solution.model.ImageType;

public class ImageServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4415973868316888066L;

	/**
	 * logger instance.
	 */
	Logger logger = Logger.getLogger (ImageServlet.class.getName());

	/**
	 * delegate instance initialized during init.
	 */
	private ImageTypeServiceDelegate imageTypeServiceDelegate = null;
	
	/**
	 * default constructor.
	 */
	public ImageServlet() {
		super();		
	}	

	/**
	 * Service method for each request.
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		logger.debug("Entering :: ImageServlet:doGet()");
		try{
			if(imageTypeServiceDelegate == null)
				return;
			ImageType imageType = imageTypeServiceDelegate.fetchImageType(Long.parseLong(request.getParameter("image_id")));
			response.setContentType("image/bmp");
			ServletOutputStream outputStream = response.getOutputStream();
			BufferedOutputStream bos = new BufferedOutputStream (outputStream);
			if(request.getParameter("imageType").equalsIgnoreCase("large")){
				if(imageType.getOriginalImage() !=null){
					bos.write(imageType.getOriginalImage());
				}
			}
			else if(request.getParameter("imageType").equalsIgnoreCase("small")){
				if(imageType.getThumbNailImage()!=null){
					bos.write(imageType.getThumbNailImage());
				}
			}
			bos.close();
			outputStream.flush();
			outputStream.close();
		}
		catch (RemoteException re){
			logger.error(re, re);
		}
		catch (ServiceBeanException sbe) {
			logger.error(sbe, sbe);
		}
	}
	
	/**
	 * Init method calling during initialization.
	 */
	public void init() throws ServletException {
		super.init();
		try{
			imageTypeServiceDelegate = new ImageTypeServiceDelegate();
		}
		catch (DelegateException de) {
			imageTypeServiceDelegate = null;
			logger.error(de,de);
		}
	}
}
